package com.cincc.config;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by liuxingmeng on 17/12/13.
 */
public class MethodReturnValueHandlerFactoryBean implements InitializingBean {

    private static final Logger LOGGER = Logger.getLogger(MethodReturnValueHandlerFactoryBean.class);

    @Autowired
    private RequestMappingHandlerAdapter adapter;

    public MethodReturnValueHandlerFactoryBean() {
    }

    public void afterPropertiesSet() throws Exception {
        this.adapter.setReturnValueHandlers(this.decorateHandlers(new ArrayList(this.adapter.getReturnValueHandlers())));
        LOGGER.info("完成统一消息封装对象初始化");
    }

    private List<HandlerMethodReturnValueHandler> decorateHandlers(List<HandlerMethodReturnValueHandler> handlers) {
        Iterator i$ = handlers.iterator();
        while(i$.hasNext()) {
            HandlerMethodReturnValueHandler handler = (HandlerMethodReturnValueHandler)i$.next();
            if(handler instanceof RequestResponseBodyMethodProcessor) {
                MethodReturnValueHandlerDelegate decorator = new MethodReturnValueHandlerDelegate(handler);
                int index = handlers.indexOf(handler);
                handlers.set(index, decorator);
                break;
            }
        }
        return handlers;
    }
}
